/**@file
   Hex buffer class
   
   @par license 
   Copyright 2012 Lu, Ken. All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 
   @author: Lu, Ken (bluewish.ken.lu@gmail.com)
**/
#include <string.h>     // memset
#include <stdio.h>      // sprintf_s

#include "hexbuffer.h"
#include "logger.h"

namespace ken {

u_HexBuffer::u_HexBuffer(void)
{
}


u_HexBuffer::~u_HexBuffer(void)
{
}

void u_HexBuffer::dump(un_t base, u32_t length, u8_t *in)
{
    char line_head[256] = {0};
    char line_tail[256] = {0};
    u32_t lines = 0;

    do {
        memset(line_head, 0, 256);
        memset(line_tail, 0, 256);
        for (u32_t index = 0; index < 16; index ++) {
            if (lines * 16 + index <= length) {
                sprintf_s(line_head, 256, "%s %02x", line_head, in[lines * 16 + index]);
                if ((in[lines * 16 + index] >= 0x21 && in[lines * 16 + index] < 0x7f) &&
                    (in[lines * 16 + index] != 0x25)) {
                    sprintf_s(line_tail, 256, "%s%c", line_tail, in[lines * 16 + index]);
                } else {
                    strcat_s(line_tail, ".");
                }
            } else {
                sprintf_s(line_tail, 256, "%s ", line_tail);
                sprintf_s(line_head, 256, "%s   ", line_head);
            }
        }

        u_print("0x%08x: %s %s", base + lines * 16, line_head, line_tail);
        lines ++;
    } while (lines * 16 < length);
}

}
